package com.example.reflect;

import android.app.Activity;
import android.view.View;

import androidx.fragment.app.Fragment;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class LogUtil {

    public static void init(Activity activity){ initLog(activity);}
    public static void init(Fragment fragment){ initLog(fragment);}
    public static void init(View view){ initLog(view);}

    private static<T> void initLog(T t) {
        //获取当前类
        Class<?> aClass = t.getClass();
        //获取当前类所有方法
        Method[] methods = aClass.getDeclaredMethods();

        for (Method method: methods){
            //获取当前类的所有注解
            Annotation[] annotations = method.getAnnotations();
            for (Annotation annotation : annotations){
                //获取注解类型
                Class<? extends Annotation> annotationType = annotation.annotationType();

                //是否存在指定类型的注释
                if (!annotationType.isAnnotationPresent(LogType.class)) {
                    continue;
                }

                LogType logType = annotationType.getAnnotation(LogType.class);
                if (logType == null) {
                    continue;
                }
                //获取log类 log
                Class type = logType.Type();


                try {
                    //获取log等级 i
                    Method usg_log_level = annotationType.getDeclaredMethod("USG_LOG_level");
                    //获取log消息 msg
                    Method msg = annotationType.getDeclaredMethod("MSG");
                    String logLevelInvoke = (String)usg_log_level.invoke(annotation);
                    String msgInvoke1 = (String)msg.invoke(annotation);
                    String name = t.getClass().getName();
//                    Log.i("MainActivity", "One")
                    //Log的子方法
                    assert logLevelInvoke != null;
                    Method logMethod = type.getMethod(logLevelInvoke,String.class,String.class);
                    logMethod.invoke(type,name,msgInvoke1);


                } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
                    e.printStackTrace();
                }

            }


        }

    }

}
